<template>
  <div class="awsCenter">
    <div style="width: 100%; height: 550px; display: flex; flex-direction: column; align-items: center; border: 0px solid black;">

      <!-- 搜索栏 -->
      <div class="awsCenter" style="width: 100%; height: 50px; margin-bottom: 20px;">
        <el-input v-model="query.name" placeholder="纹样名称" clearable style="width: 150px; margin-right: 10px;">
        </el-input>

        <el-input v-model="query.region" placeholder="所属地域" clearable style="width: 130px; margin-right: 10px;">

        </el-input>

        <el-select v-model="query.type" placeholder="纹样类型" clearable style="width: 130px; margin-right: 10px;">
          <el-option
            v-for="item in typeList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>

        <el-select v-model="query.difficultyLevel" placeholder="工艺难度" clearable style="width: 100px; margin-right: 10px;">
          <el-option label="初级" value="初级" />
          <el-option label="中级" value="中级" />
          <el-option label="高级" value="高级" />
        </el-select>

        <el-select v-model="query.reviewStatus" placeholder="状态" clearable style="width: 120px; margin-right: 10px;">
          <el-option label="待审核" value="待审核" />
          <el-option label="审核通过" value="审核通过" />
          <el-option label="审核驳回" value="审核驳回" />
        </el-select>

        <el-button type="primary" plain @click="fetchData">查询</el-button>
      </div>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        stripe
        style="width: 100%; margin-top: 10px;"
        v-loading="loading"
        :row-style="{ height: '40px' }"
      >
        <el-table-column prop="name" label="纹样名称" width="150" />
        <el-table-column prop="region" label="所属地域" width="120" />
        <el-table-column prop="type" label="纹样类型" width="120" />
        <el-table-column prop="difficultyLevel" label="难度" width="100" />
        <el-table-column prop="patternRole" label="功能角色" width="100" />
        <el-table-column prop="realname" label="上传者" width="120">

        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="180">
          <template #default="{ row }">
              {{ formatDateTime(row.uploadTime) }}
          </template>
        </el-table-column>
        <el-table-column label="纹样" width="120">
          <template #default="{ row }">
            <el-image style="width: 30px" :src="row.uploadedFilePath"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="reviewStatus" label="状态" width="120">
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button
              v-if="row.reviewStatus === '待审核'"
              type="primary"
              size="small"
              @click="openReviewDialog(row)"
            >
              审批
            </el-button>
            <el-button v-else size="small" disabled>已审</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin-top: 20px;"
        v-model:current-page="currentPage"
        :page-size="7"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handlePageChange"
      />

      <!-- 审批弹窗 -->
      <el-drawer
        v-model="showReview"
        title="纹样上传审核"
        :close-on-click-modal="false"
        @close="resetReviewForm"
        :size="800"
      >
        <el-scrollbar max-height="600px">
          <div v-if="currentItem" class="review-dialog-content">
            <!-- 纹样基本信息卡片 -->
            <el-card shadow="hover" style="margin-bottom: 20px;">
              <template #header>
                <div style="font-size: 18px; font-weight: 600; color: #1f2937;">纹样信息</div>
              </template>
              <el-descriptions :column="2" border size="medium" label-class-name="label-bold">
                <el-descriptions-item label="纹样名称">{{ currentItem.name }}</el-descriptions-item>
                <el-descriptions-item label="上传用户">{{ getUserLabel(currentItem.realname) }}</el-descriptions-item>
                <el-descriptions-item label="所属地域">{{ currentItem.region }}</el-descriptions-item>
                <el-descriptions-item label="纹样类型">{{ currentItem.type }}</el-descriptions-item>
                <el-descriptions-item label="难度等级">{{ currentItem.difficultyLevel }}</el-descriptions-item>
                <el-descriptions-item label="功能角色">{{ currentItem.patternRole }}</el-descriptions-item>
                <el-descriptions-item label="上传时间">
                  {{ formatDateTime(currentItem.uploadTime) }}
                </el-descriptions-item>
                <el-descriptions-item label="审核状态">
                  <el-tag :type="getStatusTagType(currentItem.reviewStatus)">
                    {{ currentItem.reviewStatus }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>

            <!-- 图片预览 -->
            <el-card shadow="hover" style="margin-bottom: 20px;">
              <template #header>
                <div style="font-size: 16px; font-weight: 600;">纹样预览</div>
              </template>
              <div style="display: flex; justify-content: center; padding: 10px;">
                <el-image
                  :src="currentItem.uploadedFilePath"
                  :preview-src-list="[currentItem.uploadedFilePath]"
                  fit="contain"
                  style="max-width: 100%; max-height: 300px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"
                  @error="imgOnError"
                >
                  <template #error>
                    <div style="width: 300px; height: 200px; display: flex; align-items: center; justify-content: center; background: #f5f5f5; border: 1px dashed #ccc; color: #999;">
                      加载失败
                    </div>
                  </template>
                </el-image>
              </div>
            </el-card>

            <!-- 文化信息卡片 -->
            <el-card shadow="hover" style="margin-bottom: 20px;">
              <template #header>
                <div style="font-size: 16px; font-weight: 600;">文化与工艺信息</div>
              </template>
              <el-descriptions direction="vertical" :column="1" border>
                <el-descriptions-item label="文化寓意">
                  <span style="color: #666; white-space: pre-wrap;">{{ currentItem.culturalMeaning || '暂无相关信息' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="历史背景">
                  <span style="color: #666; white-space: pre-wrap;">{{ currentItem.historicalBackground || '暂无相关信息' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="工艺流程">
                  <span style="color: #666; white-space: pre-wrap;">{{ currentItem.craftProcess || '暂无相关信息' }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>

            <!-- 审批操作 -->
            <el-card shadow="never" style="background-color: #f9fafc; border: 1px solid #e4e7ed;">
              <template #header>
                <div style="font-size: 16px; font-weight: 600; color: #1f2937;">审核操作</div>
              </template>
              <div style="display: flex; flex-direction: column; gap: 15px;">
                <el-radio-group v-model="reviewForm.reviewStatus" @change="onStatusChange">
                  <el-radio label="审核通过" border style="margin-right: 12px;">审核通过</el-radio>
                  <el-radio label="审核驳回" border>审核驳回</el-radio>
                </el-radio-group>

                <el-alert
                  v-if="reviewForm.reviewStatus === '审核通过'"
                  title="确认通过该纹样上传申请，允许其进入平台资源库。"
                  type="success"
                  show-icon
                  :closable="false"
                  style="font-size: 14px;"
                />

                <div v-if="reviewForm.reviewStatus === '审核驳回'" style="margin-top: 10px;">
                  <el-input
                    v-model="reviewForm.rejectionReason"
                    type="textarea"
                    :rows="4"
                    placeholder="请填写驳回原因，以便用户修改后重新提交"
                    maxlength="200"
                    show-word-limit
                    style="margin-top: 8px;"
                  />
                </div>
              </div>
            </el-card>
          </div>
        </el-scrollbar>

        <!-- 操作按钮 -->
        <template #footer>
          <el-button @click="showReview = false" :disabled="submitting">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="submitting">
            确认提交
          </el-button>
        </template>
      </el-drawer>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {getUploadReviewList, getUserList, reviewPattern} from '@/api/patternReview';
import {useUserStore} from "@/stores/user/user.js"; // 接口见下文

// 查询条件
const query = reactive({
  name: '',
  region: '',
  type: '',
  difficultyLevel: '',
  reviewStatus: ''
});

// 分页
const currentPage = ref(1);
const total = ref(0);
const loading = ref(false);
const tableData = ref([]);

// 用户缓存（用于显示用户名）
const userList = ref([]);
const getUserLabel = (userId) => {
  const user = userList.value.find(u => u.userId === userId);
  return user ? user.username : `用户${userId}`;
};

// 审批弹窗
const showReview = ref(false);
const currentItem = ref(null);
const submitting = ref(false);

const reviewForm = reactive({
  id: null,
  reviewStatus: '审核通过',
  rejectionReason: ''
});

// 打开审批弹窗
const openReviewDialog = (row) => {
  currentItem.value = { ...row };
  reviewForm.id = row.id;
  reviewForm.reviewStatus = '审核通过';
  reviewForm.rejectionReason = '';
  showReview.value = true;
};

// 重置表单
const resetReviewForm = () => {
  Object.assign(reviewForm, {
    id: null,
    reviewStatus: '审核通过',
    rejectionReason: ''
  });
  currentItem.value = null;
};

// 状态变化
const onStatusChange = (val) => {
  if (val === '审核通过') {
    reviewForm.rejectionReason = '';
  }
};
const userStore=useUserStore()
// 提交审核
const submitReview = async () => {
  if (!reviewForm.reviewStatus) {
    ElMessage.warning('请选择审核结果');
    return;
  }
  if (reviewForm.reviewStatus === '审核驳回' && !reviewForm.rejectionReason.trim()) {
    ElMessage.warning('请填写驳回原因');
    return;
  }

  submitting.value = true;
  try {
    const res = await reviewPattern({
      id: reviewForm.id,
      reviewStatus: reviewForm.reviewStatus,
      rejectionReason: reviewForm.rejectionReason,
      userId:userStore.user.userid
    });
    if (res.code === 200) {
      ElMessage.success('审核提交成功');
      showReview.value = false;
      await fetchData(); // 刷新列表
    } else {
      ElMessage.error(res.errMsg || '审核失败');
    }
  } catch (err) {
    ElMessage.error('网络错误');
  } finally {
    submitting.value = false;
  }
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      pageSize: 7,
      ...query
    };
    const res = await getUploadReviewList(params);
    if (res.code === 200) {
      tableData.value = res.data.data;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.errMsg);
    }
  } catch (err) {
    ElMessage.error('加载失败');
  } finally {
    loading.value = false;
  }
};

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 图片加载失败
const imgOnError = (e) => {
  e.target.src = '/img/default-pattern.png'; // 可选默认图
};



// 获取下拉选项（可从后端或静态数据获取）
const nameOptions = ref([]);
const typeList = ref(['几何纹', '动物纹','植物纹', '文字纹', '人物纹', '抽象纹']);

// 获取名称选项（可异步加载）
const loadNameOptions = async () => {
  try {
    const res = await getUploadReviewList({ pageSize: 1000 });
    if (res.code === 200) {
      const names = [...new Set(res.data.data.map(d => d.name))];
      nameOptions.value = names;
    }
  } catch (err) {
    console.error('加载名称选项失败');
  }
};

// 页面初始化
onMounted(async () => {
  await loadNameOptions();
  await fetchData();
});

// 状态标签颜色
const getStatusTagType = (status) => {
  if (status === '待审核') return 'warning';
  if (status === '审核通过') return 'success';
  return 'danger';
};

function formatDateTime(dateStr) {
  const date = new Date(dateStr);
  if (isNaN(date)) {
    throw new Error('Invalid date string');
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}


</script>

<style scoped>
.awsCenter {
  display: flex;
  align-items: center;
}

/* 描述列表加粗标签 */
.label-bold {
  font-weight: 600;
  background-color: #f7f8fa;
}

/* 弹窗内容整体样式 */
.review-dialog-content {
  padding: 10px 0;
  color: #333;
  font-size: 14px;
}

/* 卡片标题统一风格 */
.el-card__header {
  padding: 14px 20px;
  background-color: #f8f9fc;
  border-bottom: 1px solid #ebeef5;
}

/* 图片加载失败样式增强 */
.el-image__error {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}


</style>
